#include "csockmain.h"

#include "SDL/SDL_net.h"

cSockmain::cSockmain()
{
    //ctor

if(SDLNet_Init()==-1)
    {
    //cout << "SDLNet_TCP_INIT: " << endl << SDLNet_GetError();//Starts SDL_net
    exit(2);//On SDL_net error, exit with return value 2
    }

ListenerThread = NULL;

QueueInLock = NULL;
QueueInLock = SDL_CreateSemaphore( 1 );


Connected = false;
UID=0;
socket = NULL;
}

cSockmain::~cSockmain()
{
//dtor
if (socket !=NULL)SDLNet_TCP_Close(socket); // Close socket
SDLNet_Quit(); //Exit SDL_net
}

void cSockmain::OpenSocket(const char *ServerIp,Uint16 Port)
{

if(SDLNet_ResolveHost(&ip,ServerIp,Port)==-1) {
//cout << "SDLNet_TCP_ResolveHost:" << endl << SDLNet_GetError();
exit(1);
}

//cout << "OPENING CLIENT SOCKET... " << endl;
socket=SDLNet_TCP_Open(&ip);
if(!socket)
    {
    //cout << "SDLNet_TCP_open: " << endl << SDLNet_GetError();
    exit(2);
    }
//cout << "Socket opened OK..." << endl;
}


std::string cSockmain::intToString(int i)//convert a int to a string...
{
    std::stringstream TextTmp;
    std::string Text;
    TextTmp << i;
    Text = TextTmp.str();
    return Text;
}

void       cSockmain::StartThreads()
{
    //Create and run the thread
    ListenerThread = SDL_CreateThread( &listenerClient, this );
//        SenderThread = SDL_CreateThread( &SenderClient, this );
}

int cSockmain::listenerClient( void *data )
 {
int result;
char in_msg[MAXLEN];
bool quit=false;

while( quit == false )//While the program is not over
{
memset(in_msg, 0, MAXLEN); // Clear in buffer
if ( ((cSockmain*)data)->Connected)//If I'm connected...
    {
    result=SDLNet_TCP_Recv(((cSockmain*)data)->socket,in_msg,MAXLEN);//check if there is incoming data
        if(result<=0)//NO DATA
        {
        // TCP Connection is broken. (because of error or closure)
        //cout << "Socket disconnected!" << endl;
        ((cSockmain*)data)->Connected = false;
        quit = true;
        }

    ((cSockmain*)data)->textmsg.clear();
    ((cSockmain*)data)->textmsg = in_msg;

    SDL_SemWait( ((cSockmain*)data)->QueueInLock );
    ((cSockmain*)data)->InputQueue.push(((cSockmain*)data)->textmsg);//push data to the input queue
    SDL_SemPost( ((cSockmain*)data)->QueueInLock );

    }//if connected

}//while
//cout << "Ending client thread" << endl;
return 0;
}

void cSockmain::SockSend(NetCommand Command, const char* Msg)//Send message
{
    int len;
    int result;
     stringstream Out;
    Out << "/" << Command << "/" << Msg << "/";

//len=strlen(Msg)+1; // add one for the terminating NULL
len=strlen(Out.str().c_str())+1; // add one for the terminating NULL

result=SDLNet_TCP_Send(socket,Out.str().c_str(),len);
if(result<len)Connected = false;//If I can't send message, probably I'm disconnected so....
}

/*void cSockmain::CheckNewMsgs()//Displays the incoming data (pop from inputqueue)
{
    std::string NullText;
     SDL_SemWait( QueueInLock );
          while (InputQueue.size()>0)
        {
            NullText = InputQueue.front();
            ProcessMsgs(NullText);
            InputQueue.pop();
       }
       SDL_SemPost( QueueInLock );
}*/

void cSockmain::ProcessMsgs(std::string Msg)
{
       //file <<  "MSG: " << Msg  << endl;
//unsigned int x;
unsigned int y=0;
std::string NullText;
bool exit =false;




if (exit == false){
while (Msg.length()>4) //for (x=0;x<1;x++)
{
    try
    {
         //std::ofstream file( "msg.txt" );

    //  file.close();

//cout << "MSG: " << Msg << endl;
NullText.clear();
y=Msg.find_first_of("#");//find the first space
NullText = Msg.substr(0,y);
   //file <<  "MSG: " << Msg << " #: " << y << endl;
if  (y>1000) goto salir;

            if (NullText.length()>4)//Is it a command?
            {
                if (NullText.compare(0,5,"/SUID")==0) //***********************/SET Uinque ID command
                {
                    stringstream tmpss;
                    //Uint32 tmpuid;
                    tmpss << NullText.substr(5,NullText.length()-5);
                    tmpss >> UID;

                }

                if (NullText.compare(0,5,"/upda")==0) //***********************/update command
                {
                    stringstream tmpss;
                    Uint32 tmpUID;
                    std::string tmpNick;
                    int tmpImage;
                    float tmpX;
                    float tmpY;
                    int tmpAngle;
                    tmpss.clear();

                    tmpss << NullText.substr(5,NullText.length()-5);
                    tmpss >> tmpUID;
                    tmpss >> tmpImage;
                    tmpss >> tmpX;
                    tmpss >> tmpY;
                    tmpss >> tmpAngle;
                    tmpss >>  tmpNick;



 }//update
            }//tmp
}catch(...){}

Msg = Msg.substr(y+1, Msg.length()-y);
}

}//exit
salir:;

}

